<template>
  <div class="device-manage-container">
    <div class="device-wrapper">
      <div class="search-box">
        <SearchFilter :search-options="searchOptions" />
      </div>

      <div class="custom-box border-bottom">
        <template v-for="(item, index) in filterData">
          <span
            class="custom-item"
            :key="item.category"
            v-if="item.id"
          >
            <span>{{ item.name }}</span>
            <van-icon
              name="cross"
              @click="deleteCondition(item, index)"
            />
          </span>
        </template>

      </div>

      <div
        class="device-list-wrapper scroll-box"
        @scroll="scrollFn"
      >
        <ul
          class="list-box"
          v-if="deviceList.length"
        >
          <li
            v-for="item in deviceList"
            :key="item.id"
            @click="jumpDetail(item)"
          >
            <div class="device-img">
              <img
                :src="item.modelPhoto || require('@/assets/images/device_default.png')"
                alt=""
              >
            </div>
            <p class="device-status-category">
              <span
                class="color-gray"
                v-if="item.status === 1"
              >
                <i class="iconfont iconlixian"></i>
                离线
              </span>
              <span
                class="color-green"
                v-if="item.status === 2"
              >
                <i class="iconfont iconzaixian"></i>
                在线
              </span>
              <span
                class="color-red"
                v-if="item.status === 4"
              >
                <i class="iconfont iconyubaojing"></i>
                报警
              </span>
              <span>{{ coverCategory(item.modelType) }}</span>
            </p>
            <p class="device-name">{{ item.name }}</p>
            <p class="device-num">编号：{{ item.number }}</p>
          </li>
        </ul>

        <!-- 加载状态 -->
        <div
          class="loading-box"
          v-if="loading"
        >
          <p
            class="finished"
            v-if="finished"
          >没有更多了</p>
          <div
            class="loading"
            v-else
          >
            <van-loading size="14px">加载中...</van-loading>
          </div>
        </div>
      </div>

      <!-- 无数据 -->
      <div
        class="no-data-box"
        v-if="noDataState"
      >暂无数据</div>
    </div>

    <FilterDevice
      v-show="showFilterDevice"
      ref="filterDevice"
      @submit="submitFilter"
    />
  </div>
</template>

<script>
import { Loading } from 'vant';
import SearchFilter from '@/components/SearchFilter';
import FilterDevice from '@/components/FilterDevice.vue';
import { getDeviceList } from '@/api/deviceManage';

// 函数防抖
let debounceTimer;
function debounceFn(fn, delay) {
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }
  debounceTimer = setTimeout(() => {
    debounceTimer = null;
    fn();
  }, delay);
}

export default {
  name: 'DeviceManage',
  components: {
    [Loading.name]: Loading,
    SearchFilter,
    FilterDevice
  },
  data() {
    return {
      searchOptions: {
        searchKey: '',
        placeholder: '搜索设备编号/设备名称',
        handleSearch: this.reloadData,
        handleClear: this.reloadData,
        handleFilter: this.handleFilter
      },
      showFilterDevice: false,
      deviceList: [],
      typeId: '',
      modelId: '',
      groupId: '',
      status: '',
      filterData: [],
      pageIndex: 1,
      pageSize: 10,
      loading: false, //加载状态
      finished: false, //全部加载
      noDataState: false //无数据显示状态
    };
  },
  created() {
    this.getDeviceList();
  },
  methods: {
    // 获取设备列表
    getDeviceList() {
      getDeviceList({
        name: this.searchOptions.searchKey,
        typeId: this.typeId,
        modelId: this.modelId,
        groupId: this.groupId,
        status: this.status,
        page: this.pageIndex,
        page_size: this.pageSize
      }).then(res => {
        this.loading = false;
        let data = res.data.list || [];
        this.deviceList = this.deviceList.concat(data);
        // 无数据
        if (this.deviceList.length <= 0 && this.pageIndex === 1) {
          this.noDataState = true;
          this.loading = false;
          this.finished = false;
        }

        // 全部加载完成
        if (this.pageIndex > 1 && res.data.list.length < this.pageSize) {
          this.finished = true;
        }
      });
    },
    // 重载数据
    reloadData() {
      this.pageIndex = 1;
      this.deviceList = [];
      this.loading = false;
      this.finished = false;
      this.noDataState = false;
      this.getDeviceList();
    },
    // 滚动事件
    scrollFn(e) {
      let scrollTop = document.querySelector('.device-list-wrapper').scrollTop;
      let clientHeight = document.querySelector('.device-list-wrapper').clientHeight;
      let scrollHeight = document.querySelector('.device-list-wrapper').scrollHeight;

      if (scrollTop + clientHeight >= scrollHeight) {
        debounceFn(this.onLoadMore, 300);
      }
    },
    // 加载更多
    onLoadMore() {
      this.loading = true;
      if (!this.finished) {
        // 异步更新数据
        setTimeout(() => {
          this.pageIndex++;
          this.getDeviceList();
        }, 500);
      }
    },
    // 转换类型为文字
    coverCategory(type) {
      let obj = {
        1: '搬运类',
        2: '输送类',
        3: '包装类',
        4: '其他类'
      };
      return obj[type];
    },
    // 确定筛选条件
    submitFilter(data) {
      console.log('data---', data);
      this.filterData = data;

      data.map(item => {
        switch (item.category) {
          case 'type':
            this.typeId = item.id;
            break;
          case 'status':
            this.status = item.id;
            break;
          case 'model':
            this.modelId = item.id;
            break;
          case 'group':
            this.groupId = item.id;
            break;
        }
      });
      this.showFilterDevice = false;
      this.reloadData();
    },
    // 去详情
    jumpDetail(item) {
      if (this.$checkBtnPermission('deviceCenter:deviceManage:list:detail')) {
        this.$router.push({
          name: 'deviceDetail',
          query: {
            id: item.id,
            deviceName: item.name,
            videoId: item.videoId,
            modelId: item.modelId,
            modelName: item.model_name,
            controlPwd: item.controlPwd
          }
        });
      } else {
        this.$toast(this.$store.state.noDetailPermissionText);
      }
    },
    // 打开筛选
    handleFilter() {
      this.showFilterDevice = true;
    },
    // 删除筛选条件
    deleteCondition(item, index) {
      switch (item.category) {
        case 'type':
          this.typeId = '';
          this.$refs.filterDevice.typeId = '';
          this.$refs.filterDevice.typeName = '';
          this.$refs.filterDevice.typeData.map(item => {
            item.checked = false;
          });
          break;
        case 'status':
          this.status = '';
          this.$refs.filterDevice.status = '';
          this.$refs.filterDevice.statusName = '';
          this.$refs.filterDevice.statusData.map(item => {
            item.checked = false;
          });
          break;
        case 'model':
          this.modelId = '';
          this.$refs.filterDevice.modelId = '';
          this.$refs.filterDevice.modelName = '';
          this.$refs.filterDevice.modelData.map(item => {
            item.checked = false;
          });
          break;
        case 'group':
          this.groupId = '';
          this.$refs.filterDevice.groupId = '';
          this.$refs.filterDevice.groupName = '';
          this.$refs.filterDevice.groupData.map(item => {
            item.checked = false;
          });
          this.$refs.filterDevice.backData.map(item => {
            item.map(subItem => {
              subItem.checked = false;
            });
          });
          break;
      }
      this.filterData.splice(index, 1);
      this.reloadData();
    }
  }
};
</script>

<style lang="scss" scoped>
.device-manage-container {
  width: 100%;
  height: 100%;

  .device-wrapper {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    .search-box {
      flex-shrink: 0;
    }

    .custom-box {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      width: 100%;
      padding: 0 0.426667rem;
      background-color: #fff;

      .custom-item {
        margin-right: 0.213333rem;
        margin-bottom: 0.213333rem;
        padding: 0.106667rem 0.213333rem;
        color: var(--color-deep-gray);
        font-size: 0.32rem;
        background-color: #f9f9f9;
        border-radius: 0.106667rem;

        span {
          margin-right: 0.266667rem;
        }

        .van-icon {
          color: #ccc;
        }
      }
    }

    .device-list-wrapper {
      display: flex;
      flex-direction: column;

      .loading-box {
        display: flex;
        justify-content: center;
      }
    }

    .list-box {
      flex: 1;
      display: grid;
      grid-template-columns: repeat(auto-fill, 4.88rem);
      column-gap: 0.213333rem;
      row-gap: 0.213333rem;
      width: 100%;
      padding: 0.213333rem 0;

      li {
        // width: 4.88rem;
        // margin-bottom: 0.213333rem;
        padding: 0.32rem;
        background-color: #fff;

        &:nth-of-type(odd) {
          float: left;
        }

        &:nth-of-type(even) {
          float: right;
        }

        .device-img {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;
          height: 2.293333rem;
          margin-bottom: 0.053333rem;
          padding: 0.213333rem 0.88rem;
          border: 1px solid #ebeef5;
          overflow: hidden;

          img {
            max-width: 100%;
            height: 100%;
          }
        }

        .device-status-category {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 0.213333rem;

          span {
            &:first-of-type {
              font-size: 0.346667rem;

              i {
                font-size: 0.346667rem;
              }
            }

            &:last-of-type {
              display: flex;
              justify-content: center;
              align-items: center;
              padding: 0.053333rem 0.16rem;
              color: #666666;
              font-size: 0.32rem;
              border-radius: 100em;
              background-color: #f6f6f6;
            }
          }
        }

        .device-name {
          margin: 0.266667rem 0;
          line-height: 0.533333rem;
          color: #333333;
          font-size: 0.4rem;
        }

        .device-num {
          color: #999999;
          font-size: 0.346667rem;
        }
      }
    }

    // 加载更多
    .loading-box {
      width: 100%;

      .finished {
        padding: 0.213333rem 0;
        color: var(--color-gray);
        font-size: 0.32rem;
        text-align: center;
      }

      .loading {
        padding: 0.213333rem 0;
        text-align: center;
      }
    }

    .no-data-box {
      padding: 0.32rem 0.426667rem;
      text-align: center;
      color: var(--color-gray);
      font-size: 0.373333rem;
    }
  }
}
</style>